package com.by.cloud.interceptor;

/**
 * @author: linweirui
 * @date: 2024/12/11 10:03
 */

import com.by.cloud.constants.JwtClaimsConstant;
import com.by.cloud.common.BaseContext;
import com.by.cloud.exception.BusinessException;
import com.by.cloud.exception.ErrorCode;
import com.by.cloud.common.JwtProperties;
import com.by.cloud.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户jwt拦截器
 */
@Component
@Slf4j
public class JwtTokenUserInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 在拦截的方法之前进行jwt校验并存放用户信息
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //判断当前是否是controller方法 HandlerMethod指一个具体的处理器方法
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截的不是动态方法，直接放行
            return true;
        }
        //从请求头获取令牌
        String authToken = request.getHeader(jwtProperties.getUserTokenName());
        try {
            //校验令牌
            log.info("jwt校验,{}", authToken);
            Claims claims = JwtUtil.parseJwt(jwtProperties.getUserSecretKey(), authToken);
            Long userId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
            BaseContext.setCurrentId(userId);
            log.info("当前用户信息id,{}", userId);
            //放行
            return true;
        } catch (Exception e) {
            //校验不通过，响应错误状态码
            response.setStatus(ErrorCode.NOT_LOGIN_ERROR.getCode());
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
    }

    /**
     * 调用结束，释放threadLocal里面的用户信息资源
     * 避免资源浪费
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //释放threadLocal里面的用户信息资源
        if (BaseContext.getCurrentId() != null) {
            BaseContext.removeCurrentId();
        }
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

}
